package com.servlet;

import com.alibaba.fastjson.JSONObject;
import com.dao.BuildDao;
import com.dao.ExchangeDao;
import com.dao.RoomDao;
import com.model.*;
import com.util.DbUtil;
import com.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

/**
 * 调换管理
 * @author : wangjg
 * @date : 2023/11/1 16:24
 */
@WebServlet(name = "ExchangeServlet")
public class ExchangeServlet extends HttpServlet {

    DbUtil dbUtil = new DbUtil();
    ExchangeDao exchangeDao = new ExchangeDao();
    BuildDao buildDao = new BuildDao();
    RoomDao roomDao = new RoomDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if("getRoomListByBuildId".equals(action)){
            getRoomListByBuildId(request,response);
            return;
        }
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        Object currentUserType = session.getAttribute("currentUserType");
        String searchText = request.getParameter("searchText");
        String buildId = request.getParameter("buildId");
        String searchType = request.getParameter("searchType");
        String action = request.getParameter("action");
        String page = request.getParameter("page");
        if(StringUtil.isEmpty(page)){
            page = "0";
        }
        Exchange exchange = new Exchange();
        if("preSave".equals(action)) {
            exchangePreSave(request, response);
            return;
        }else if("save".equals(action)){
            exchangeSave(request, response);
            return;
        } else if("delete".equals(action)){
            exchangeDelete(request, response);
            return;
        } else if("pass".equals(action)){
            exchangePass(request, response);
            return;
        }else if("reject".equals(action)){
            exchangeReject(request, response);
            return;
        } else if("list".equals(action)) {
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    exchange.setUserName(searchText);
                }
            }
            if(StringUtil.isNotEmpty(buildId)) {
                exchange.setBuildId(Integer.parseInt(buildId));
            }
            session.removeAttribute("searchText");
            session.removeAttribute("searchType");
            session.removeAttribute("buildId");
            request.setAttribute("searchText", searchText);
            request.setAttribute("searchType", searchType);
            request.setAttribute("buildId", buildId);
        } else if("search".equals(action)){
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    exchange.setUserName(searchText);
                }
                session.setAttribute("searchText", searchText);
                session.setAttribute("searchType", searchType);
            } else {
                session.removeAttribute("searchText");
                session.removeAttribute("searchType");
            }
            if(StringUtil.isNotEmpty(buildId)) {
                exchange.setBuildId(Integer.parseInt(buildId));
                session.setAttribute("buildId", buildId);
            }else {
                session.removeAttribute("buildId");
            }
        }else{
            if(StringUtil.isEmpty(searchText) && StringUtil.isEmpty(buildId)) {
                Object o1 = session.getAttribute("searchText");
                Object o2 = session.getAttribute("searchType");
                Object o3 = session.getAttribute("buildId");
                if(o1!=null) {
                    if("name".equals(o2)) {
                        exchange.setUserName((String)o1);
                    }
                }
                if(o3 != null) {
                    exchange.setBuildId(Integer.parseInt((String)o3));
                }
            }
        }
        Connection con = null;
        PageBean pageBean = new PageBean(Integer.parseInt(page), 5);
        request.setAttribute("pageSize", pageBean.getPageSize());
        request.setAttribute("page", pageBean.getPage());
        try {
            con=dbUtil.getCon();
            List<Exchange> exchangeList;
            List<Build> buildList = buildDao.buildList(con, null, new Build());
            if("admin".equals(currentUserType)) {
                exchangeList = exchangeDao.exchangeList(con, pageBean,exchange);
                int total = exchangeDao.exchangeCount(con, exchange);
                String pageCode = this.genPage(total, Integer.parseInt(page),5);
                request.setAttribute("pageCode", pageCode);
                request.setAttribute("buildList", buildList);
                request.setAttribute("exchangeList", exchangeList);
                request.setAttribute("mainPage", "admin/exchange.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }else if("student".equals(currentUserType)) {
                User student = (User)(session.getAttribute("currentUser"));
                exchange.setUserId(student.getId());
                exchangeList = exchangeDao.exchangeList(con, pageBean,exchange);
                int total = exchangeDao.exchangeCount(con, exchange);
                String pageCode = this.genPage(total, Integer.parseInt(page),5);
                request.setAttribute("pageCode", pageCode);
                request.setAttribute("buildList", buildList);
                request.setAttribute("exchangeList", exchangeList);
                request.setAttribute("mainPage", "student/exchange.jsp");
                request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void exchangeDelete(HttpServletRequest request,
                              HttpServletResponse response) {
        String exchangeId = request.getParameter("exchangeId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            exchangeDao.deleteExchange(con, exchangeId);
            request.getRequestDispatcher("exchange?action=list").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void exchangeSave(HttpServletRequest request,
                            HttpServletResponse response) {
        String buildId = request.getParameter("buildId");
        String roomId = request.getParameter("roomId");
        String date = request.getParameter("date");
        String reason = request.getParameter("reason");

        Connection con = null;
        try {
            con = dbUtil.getCon();
            HttpSession session = request.getSession();
            User student = (User)(session.getAttribute("currentUser"));
            Build build = buildDao.buildInfo(con, Integer.parseInt(buildId));
            Room room = roomDao.roomInfo(con,Integer.parseInt(roomId));
            Exchange exchange = new Exchange(student.getId(),student.getUserName(),student.getSex(),
                    Integer.parseInt(buildId),build.getName(),Integer.parseInt(roomId),room.getNum(),reason,date,"审核中");
            int saveNum = exchangeDao.addExchange(con,exchange);
            if(saveNum > 0) {
                request.getRequestDispatcher("exchange?action=list").forward(request, response);
            } else {
                request.setAttribute("error", "保存失败");
                request.setAttribute("mainPage", "student/exchangeSave.jsp");
                request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void exchangePreSave(HttpServletRequest request,
                               HttpServletResponse response)throws ServletException, IOException {
        String buildId = request.getParameter("buildId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            HttpSession session = request.getSession();
            User currentUser = (User)(session.getAttribute("currentUser"));
            List<Build> buildList = buildDao.buildList(con, null, new Build());
            if(StringUtil.isNotEmpty(buildId)){
                List<Room> roomList = roomDao.roomList(con, null, new Room(Integer.parseInt(buildId)));
                request.setAttribute("roomList", roomList);
            }
            request.setAttribute("buildList", buildList);
            request.setAttribute("currentUser", currentUser);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        request.setAttribute("mainPage", "student/exchangeSave.jsp");
        request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
    }

    private void getRoomListByBuildId(HttpServletRequest request,
                                 HttpServletResponse response)throws ServletException, IOException {
        String buildId = request.getParameter("buildId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            HttpSession session = request.getSession();
            User currentUser = (User) (session.getAttribute("currentUser"));
            if (StringUtil.isNotEmpty(buildId)) {
                List<Room> roomList = roomDao.roomList(con, null, new Room(Integer.parseInt(buildId)));
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("roomList", roomList);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(jsonObject.toJSONString());
            }
            request.setAttribute("currentUser", currentUser);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void exchangePass(HttpServletRequest request,
                                HttpServletResponse response) {
        String exchangeId = request.getParameter("exchangeId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            Exchange exchange = exchangeDao.exchangeInfo(con, Integer.parseInt(exchangeId));
            exchange.setStatus("已通过");
            exchangeDao.updateExchange(con, exchange);
            request.getRequestDispatcher("exchange?action=list").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void exchangeReject(HttpServletRequest request,
                              HttpServletResponse response) {
        String exchangeId = request.getParameter("exchangeId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            Exchange exchange = exchangeDao.exchangeInfo(con, Integer.parseInt(exchangeId));
            exchange.setStatus("已驳回");
            exchangeDao.updateExchange(con, exchange);
            request.getRequestDispatcher("exchange?action=list").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private String genPage(int totalNum, int currentPage, int pageSize){
        int totalPage = totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
        StringBuilder pageCode = new StringBuilder();
        pageCode.append("<li><a href='exchange?page=1'>首页</a></li>");
        if(currentPage==1) {
            pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
        }else {
            pageCode.append("<li><a href='exchange?page=").append(currentPage - 1).append("'>上一页</a></li>");
        }
        for(int i=currentPage-2;i<=currentPage+2;i++) {
            if(i<1||i>totalPage) {
                continue;
            }
            if(i==currentPage) {
                pageCode.append("<li class='active'><a href='#'>").append(i).append("</a></li>");
            } else {
                pageCode.append("<li><a href='exchange?page=").append(i).append("'>").append(i).append("</a></li>");
            }
        }
        if(currentPage==totalPage) {
            pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
        } else {
            pageCode.append("<li><a href='exchange?page=").append(currentPage + 1).append("'>下一页</a></li>");
        }
        pageCode.append("<li><a href='exchange?page=").append(totalPage).append("'>尾页</a></li>");
        return pageCode.toString();
    }
}
